package openase.audiosearch.processor;

import openase.audio.AudioFingerprint;
import openase.audio.AudioFingerprintStorageFacade;
import openase.audio.StorageException;
import openase.audio.fingerprinthash.FingerprintGeneratorFacade;
import openase.audiosearch.AudioSearchProperties;
import openase.audiosearch.comm.request.AudioRegistration;
import openase.audiosearch.comm.response.RegistrationSuccessful;
import openase.audiosearch.comm.response.Response;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class AudioRegistrationRequestProcessor {

	private static final Log logger = LogFactory.getLog(AudioRegistrationRequestProcessor.class);

	public static Response process(AudioRegistration request) {
		final String name = request.getName();
		final byte[] tdAudio = request.getAudioInput();

		logger.info("Starting to generate fingerprints for '" + name + "'");
		long ini_fp = now();
		final AudioFingerprint[] fps = FingerprintGeneratorFacade.generateFingerprints(tdAudio, AudioSearchProperties.CHUNK_SIZE);
		long end_fp = now();
		logger.info("Generate fingerprints for '" + name + "' took " + (end_fp - ini_fp) + "ms");

		try {
			logger.info("Starting to store audio and fingerprints for '" + name + "'");
			long ini_store = now();
			AudioFingerprintStorageFacade.store(name, fps);
			long end_store = now();
			logger.info("Store audio and fingerprints for '" + name + "' took " + (end_store - ini_store) + "ms");
		} catch (StorageException se) {
			logger.error("Error storing audio and fingerprints for '" + name + "': " + se.getMessage(), se);
			throw new RuntimeException(se);
		}

		return new RegistrationSuccessful();
	}

	private static long now() {
		return System.currentTimeMillis();
	}

}
